<template>
  <div class="user-edit-container">
    <el-card shadow="hover">
      <template #header>
        <div class="card-header">
          <span class="title">{{ form.id ? '编辑用户信息' : '创建新用户' }}</span>
          <el-button
              type="primary"
              @click="goBack"
              icon="Back"
              plain
          >
            返回用户列表
          </el-button>
        </div>
      </template>

      <el-form
          :model="form"
          :rules="rules"
          ref="userForm"
          label-position="left"
          label-width="120px"
          class="user-form"
      >
        <el-form-item label="用户名" prop="username">
          <el-input
              v-model="form.username"
              placeholder="请输入3-20位用户名"
              clearable
              :prefix-icon="User"
          />
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input
              v-model="form.password"
              type="password"
              :placeholder="form.id ? '留空则不修改密码' : '请输入6-20位密码'"
              show-password
              :prefix-icon="Lock"
          />
        </el-form-item>

        <el-form-item label="手机号码" prop="phone">
          <el-input
              v-model="form.phone"
              placeholder="请输入11位手机号"
              maxlength="11"
              :prefix-icon="Iphone"
          />
        </el-form-item>

        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="用户角色" prop="role">
              <el-select
                  v-model="form.role"
                  placeholder="请选择用户角色"
                  class="full-width"
                  :prefix-icon="UserFilled"
              >
                <el-option
                    v-for="role in roleOptions"
                    :key="role.value"
                    :label="role.label"
                    :value="role.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="权限级别" prop="permission">
              <el-select
                  v-model="form.permission"
                  placeholder="请选择权限级别"
                  class="full-width"
                  :prefix-icon="Key"
              >
                <el-option
                    v-for="perm in permissionOptions"
                    :key="perm.value"
                    :label="perm.label"
                    :value="perm.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="账号状态" prop="status">
          <el-switch
              v-model="form.status"
              :active-value="1"
              :inactive-value="0"
              active-text="启用"
              inactive-text="禁用"
              inline-prompt
          />
        </el-form-item>

        <el-form-item class="form-actions">
          <el-button
              type="primary"
              @click="submitForm"
              :loading="submitting"
              :icon="Check"
          >
            {{ submitting ? '提交中...' : '确认保存' }}
          </el-button>
          <el-button
              @click="resetForm"
              :icon="Refresh"
          >
            重置表单
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import {
  User, Lock, Iphone, UserFilled, Key,
  Back, Check, Refresh
} from '@element-plus/icons-vue'

const route = useRoute()
const router = useRouter()
const userForm = ref(null)

const BASE_URL = 'http://localhost:8080'

const form = ref({
  id: null,
  username: '',
  password: '',
  phone: '',
  role: 0,
  permission: 0,
  status: 1
})

const roleOptions = [
  { value: 0, label: '普通用户' },
  { value: 1, label: '商家用户' },
  { value: 2, label: '管理员' }
]

const permissionOptions = [
  { value: 0, label: '无权限' },
  { value: 1, label: '只读权限' },
  { value: 2, label: '读写权限' }
]

const rules = {
  username: [
    { required: true, message: '用户名不能为空', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在3到20个字符', trigger: 'blur' },
    {
      pattern: /^[a-zA-Z0-9_]+$/,
      message: '只能包含字母、数字和下划线',
      trigger: 'blur'
    }
  ],
  password: [
    {
      validator: (rule, value, callback) => {
        if (form.value.id && !value) {
          callback()
        } else if (!value) {
          callback(new Error('请输入密码'))
        } else if (value.length < 6 || value.length > 20) {
          callback(new Error('密码长度6-20位'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  phone: [
    { required: true, message: '手机号不能为空', trigger: 'blur' },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: '请输入正确的11位手机号',
      trigger: 'blur'
    }
  ],
  role: [
    { required: true, message: '请选择用户角色', trigger: 'change' }
  ],
  permission: [
    { required: true, message: '请选择权限级别', trigger: 'change' }
  ]
}

const submitting = ref(false)

const fetchUser = async (id) => {
  try {
    const { data } = await axios.get(`${BASE_URL}/api/v1/admin/selAllUser`)
    const user = data.data?.find(item => item.id === Number(id))

    if (!user) {
      ElMessage.error('未找到该用户信息')
      return router.push('/users')
    }

    form.value = {
      id: user.id,
      username: user.username,
      password: '',
      phone: user.phone,
      role: user.role,
      permission: user.permission,
      status: user.status
    }
  } catch (error) {
    console.error('获取用户信息失败:', error)
    ElMessage.error(`获取用户信息失败: ${error.message}`)
    router.push('/users')
  }
}

const submitForm = async () => {
  try {
    await userForm.value.validate();
    submitting.value = true;

    const payload = { ...form.value };
    if (payload.id && !payload.password) {
      delete payload.password;
    }

    const { data } = await axios.post(
        `${BASE_URL}/api/v1/admin/revise`,
        payload
    );

    if (data.code === 200) {
      ElMessage.success({
        message: '用户信息保存成功',
        duration: 1500,
        onClose: () => {
          router.push('/users').then(() => {
            // 触发刷新用户列表的事件或重新获取数据
            const event = new CustomEvent('refreshUsers');
            window.dispatchEvent(event);
          });
        }
      });
    } else {
      ElMessage.error(data.message || '保存失败');
    }
  } catch (error) {
    console.error('保存失败:', error);
    const errorMsg = error.response?.data?.message ||
        error.message ||
        '请求失败，请检查网络';
    ElMessage.error(errorMsg);
  } finally {
    submitting.value = false;
  }
}

const resetForm = () => {
  if (form.value.id) {
    fetchUser(form.value.id)
  } else {
    form.value = {
      id: null,
      username: '',
      password: '',
      phone: '',
      role: 0,
      permission: 0,
      status: 1
    }
  }
}

const goBack = () => {
  router.push('/users')
}

onMounted(() => {
  if (route.query.id) {
    fetchUser(route.query.id)
  }
})
</script>

<style scoped>
.user-edit-container {
  max-width: 900px;
  margin: 0 auto;
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title {
  font-size: 18px;
  font-weight: 600;
  color: var(--el-text-color-primary);
}

.user-form {
  padding: 20px 40px;
}

.full-width {
  width: 100%;
}

.form-actions {
  margin-top: 30px;
  display: flex;
  justify-content: center;
  gap: 20px;
}

.el-form-item {
  margin-bottom: 22px;
}

:deep(.el-input__wrapper) {
  border-radius: 8px;
}

:deep(.el-select .el-input__wrapper) {
  box-shadow: 0 0 0 1px var(--el-border-color) inset;
}
</style>